// editor.js
// 修改初始化编辑器内容函数
window.onload = function() {
    const editor = document.getElementById('editor');
    
    // 清空自动创建的块
    editor.innerHTML = '';
    
    // 创建可编辑标题行
    const titleBlock = document.createElement('div');
    titleBlock.className = 'title-block';
    titleBlock.contentEditable = true;
    titleBlock.textContent = '新页面';
    titleBlock.dataset.modified = 'false'; // 初始未修改状态
    editor.appendChild(titleBlock);

    // 设置初始光标位置
    setTimeout(() => {
        const range = document.createRange();
        const textNode = titleBlock.firstChild;
        range.setStart(textNode, 0); // 定位到开头
        range.collapse(true);
        const selection = window.getSelection();
        selection.removeAllRanges();
        selection.addRange(range);
    }, 50); // 稍延迟确保生效

    // 标题输入监听
    titleBlock.addEventListener('input', () => {
        const isModified = titleBlock.textContent !== '新页面';
        titleBlock.dataset.modified = isModified;
        
        // 自动恢复默认文字
        if (titleBlock.textContent.trim() === '') {
            titleBlock.textContent = '新页面';
            const range = document.createRange();
            range.selectNodeContents(titleBlock);
            range.collapse(true);
            const selection = window.getSelection();
            selection.removeAllRanges();
            selection.addRange(range);
        }
    });

    // 修改标题行点击处理
    titleBlock.addEventListener('click', (e) => {
        // 只需要确保标题获得焦点即可
        // 浏览器会自动处理光标位置
        titleBlock.focus();
        
        // 阻止事件冒泡
        e.stopPropagation();
    });

    // 确保这是唯一的回车键处理
    editor.addEventListener('keydown', handleEnterKey);

    // 初始化其他功能
    startBackgroundSlideshow();
    setupAIPrompt();
    initImageResizing();
    initBlockHandling();
    setupPasteHandler();
    setupDragAndDrop();
    setupBookmarks();
    initColorPicker();
};

// 提取公共处理函数
function handleEnterKey(e) {
    // 检查是否在AI输入框内，如果是则不处理
    if (e.target.closest('.ai-input-container')) {
        return; // 让AI输入框自己处理Enter键
    }
    
    if (e.key === 'Enter' && !e.shiftKey) {
        e.preventDefault();
        const selection = window.getSelection();
        const range = selection.getRangeAt(0);
        
        // 修复点1：更精确判断是否在标题行
        const titleBlock = document.querySelector('.title-block');
        const isInTitle = titleBlock && 
                         (range.startContainer === titleBlock || 
                          range.startContainer.parentNode === titleBlock);

        if (isInTitle) {
            // 修复点2：确保在标题行最后创建新块
            const newBlock = createBlock();
            titleBlock.insertAdjacentElement('afterend', newBlock);

            // 设置光标到新块
            const newTextBlock = newBlock.querySelector('.text-block');
            const newRange = document.createRange();
            newRange.selectNodeContents(newTextBlock);
            newRange.collapse(true);
            
            selection.removeAllRanges();
            selection.addRange(newRange);
            newTextBlock.focus();
        } else {
            // 原有块处理逻辑
            const block = range.startContainer.nodeType === Node.TEXT_NODE
                ? range.startContainer.parentNode.closest('.block')
                : range.startContainer.closest('.block');

            if (block) {
                // 创建新块并插入到当前块之后
                const newBlock = createBlock();
                block.after(newBlock);

                // 设置光标到新块的文本区域
                const newTextBlock = newBlock.querySelector('.text-block');
                newTextBlock.focus();
                
                // 创建新的 range 并设置光标位置
                const newRange = document.createRange();
                newRange.setStart(newTextBlock, 0);
                newRange.collapse(true);
                
                // 清除当前选区并添加新 range
                selection.removeAllRanges();
                selection.addRange(newRange);
            }
        }
    }
}

// 修改初始化块处理函数
function initBlockHandling() {
    const editor = document.getElementById('editor');
    
    // 防止在非文本块区域编辑
    editor.addEventListener('click', (e) => {
        if (e.target === editor) {
            const lastBlock = editor.querySelector('.block:last-child .text-block');
            if (lastBlock) {
                lastBlock.focus();
            }
        }
    });
}

// 修改创建新块函数，确保总是有一个可编辑的块
function ensureEditableBlock() {
    const editor = document.getElementById('editor');
    let blocks = editor.querySelectorAll('.block');

    if (blocks.length === 0) {
        const newBlock = createBlock();
        editor.appendChild(newBlock);
        blocks = editor.querySelectorAll('.block');
    }

    // 确保最后一个块有内容
    const lastBlock = blocks[blocks.length - 1];
    const textBlock = lastBlock.querySelector('.text-block');
    if (!textBlock.textContent.trim()) {
        textBlock.innerHTML = '<br>';
    }
    return lastBlock;
}

// 修改创建块函数
function createBlock() {
    const block = document.createElement('div');
    block.className = 'block';
    block.tabIndex = -1; // 添加可聚焦属性
    
    // 添加点击事件监听
    block.addEventListener('click', (e) => {
        e.currentTarget.focus(); // 点击时聚焦
    });
    
    block.dataset.blockId = Date.now();

    // 创建拖动手柄
    const dragHandle = document.createElement('div');
    dragHandle.className = 'block-drag-handle';
    dragHandle.innerHTML = '⋮⋮';
    dragHandle.contentEditable = false; // 明确禁止编辑

    // 创建文本块
    const textBlock = document.createElement('div');
    textBlock.className = 'text-block';
    textBlock.contentEditable = true;
    textBlock.innerHTML = '<br>';

    // 组装块
    block.appendChild(dragHandle);
    block.appendChild(textBlock);

    // 添加事件处理
    block.addEventListener('keydown', (e) => {
        if (e.key === 'Backspace' || e.key === 'Delete') {
            const selection = window.getSelection();
            if (!selection.rangeCount) return;

            const range = selection.getRangeAt(0);
            // 检查是否在拖动手柄位置
            if (range.startContainer === dragHandle || range.startContainer.parentNode === dragHandle) {
                e.preventDefault();
                // 将光标移动到文本块开头
                const newRange = document.createRange();
                newRange.selectNodeContents(textBlock);
                newRange.collapse(true);
                selection.removeAllRanges();
                selection.addRange(newRange);
            }
        }
    });

    return block;
}

// 修改拖放功能
// 完全重写块拖放逻辑
function setupDragAndDrop() {
    const editor = document.getElementById('editor');
    let dragHandle = null;
    let currentBlock = null;
    let placeholder = null;
    let isDragging = false;

    // 创建占位符
    function createPlaceholder() {
        const div = document.createElement('div');
        div.className = 'block-placeholder';
        return div;
    }

    editor.addEventListener('mousedown', (e) => {
        if (e.target.closest('.block-drag-handle')) {
            e.preventDefault();
            currentBlock = e.target.closest('.block');
            dragHandle = e.target;
            isDragging = true;

            // 创建占位符
            placeholder = createPlaceholder();
            currentBlock.parentNode.insertBefore(placeholder, currentBlock.nextSibling);

            currentBlock.classList.add('dragging');
            document.body.style.cursor = 'grabbing';
        }
    });

    document.addEventListener('mousemove', (e) => {
        if (!isDragging) return;

        const blocks = [...editor.querySelectorAll('.block:not(.dragging)')];
        const closest = blocks.reduce((closest, block) => {
            const box = block.getBoundingClientRect();
            const offset = e.clientY - box.top - box.height/2;

            if (offset < 0 && offset > closest.offset) {
                return { offset: offset, element: block };
            } else {
                return closest;
            }
        }, { offset: Number.NEGATIVE_INFINITY });

        if (placeholder) {
            placeholder.classList.remove('visible');
            if (closest.element) {
                closest.element.parentNode.insertBefore(placeholder, closest.element);
            } else {
                editor.appendChild(placeholder);
            }
            placeholder.classList.add('visible');
        }
    });

    document.addEventListener('mouseup', (e) => {
        if (!isDragging) return;

        isDragging = false;
        document.body.style.cursor = '';
        currentBlock.classList.remove('dragging');

        if (placeholder) {
            placeholder.parentNode.insertBefore(currentBlock, placeholder);
            placeholder.parentNode.removeChild(placeholder);
            placeholder = null;
        }

        // 触发自动保存
        autoSave();
    });
}

// 格式化文本
function formatText(command) {
    document.execCommand(command, false, null);
    
    // 保存更改
    if (typeof DataService !== 'undefined') {
        DataService.savePageContent();
    }
}

// 自动保存
function autoSave() {
    // 自动保存内容
    if (typeof DataService !== 'undefined') {
        DataService.savePageContent();
    }
}

// 手动保存
function saveContent() {
    // 调用DataService中的强制保存函数
    if (typeof DataService !== 'undefined') {
        DataService.forceSaveAllData();
    } else {
        console.error('找不到DataService函数');
    }
}

// 创建新块
function createNewBlockAfter(referenceNode) {
    const block = createBlock();
    
    if (referenceNode) {
        referenceNode.parentNode.insertBefore(block, referenceNode.nextSibling);
    } else {
        document.getElementById('editor').appendChild(block);
    }
    
    // 聚焦到新块
    const textBlock = block.querySelector('.text-block');
    if (textBlock) {
        textBlock.focus();
    }
    
    // 保存更改
    if (typeof DataService !== 'undefined') {
        DataService.savePageContent();
    }
    
    return block;
}

// 切换颜色选择器
function toggleColorPicker() {
    const colorPicker = document.getElementById('colorPicker');
    colorPicker.style.display = colorPicker.style.display === 'none' ? 'flex' : 'none';
}

// 初始化颜色选择器
function initColorPicker() {
    const colorOptions = document.querySelectorAll('.color-option');
    const editorContainer = document.querySelector('.editor-container');
    
    colorOptions.forEach(option => {
        option.addEventListener('click', function() {
            const color = this.getAttribute('data-color');
            editorContainer.style.backgroundColor = color;
            document.getElementById('colorPicker').style.display = 'none';
            
            // 保存颜色偏好到localStorage
            localStorage.setItem('editorBgColor', color);
        });
    });
    
    // 加载保存的颜色偏好
    const savedColor = localStorage.getItem('editorBgColor');
    if (savedColor) {
        editorContainer.style.backgroundColor = savedColor;
    }
}

// 初始化编辑器
function initEditor() {
    initColorPicker();
    initBlockHandling();
    setupPasteHandler();
    setupDragAndDrop();
    
    // 添加编辑器输入事件监听
    const editor = document.getElementById('editor');
    if (editor) {
        editor.addEventListener('input', autoSave);
    }
}

// 在DOM加载完成后初始化
document.addEventListener('DOMContentLoaded', initEditor);

// 导出公共函数
window.formatText = formatText;
window.autoSave = autoSave;
window.saveContent = saveContent;
window.createNewBlockAfter = createNewBlockAfter;
window.toggleColorPicker = toggleColorPicker; 